package com.example.note;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.note.activity.DiaryEditActivity;

import com.example.note.adapter.DiaryAdapter;
import com.example.note.database.DiaryEntity;
import com.example.note.viewmodel.DiaryViewModel;
import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.textfield.TextInputEditText;

import java.util.List;

public class MainActivity extends AppCompatActivity implements DiaryAdapter.OnDiaryClickListener {

    private MaterialToolbar toolbar;
    private TextInputEditText etSearch;
    private RecyclerView recyclerView;
    private LinearLayout emptyStateLayout;
    private FloatingActionButton fabAdd;
    
    private DiaryViewModel diaryViewModel;
    private DiaryAdapter diaryAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        
        initViews();
        initViewModel();
        setupRecyclerView();
        setupListeners();
        observeData();
    }
    
    private void initViews() {
        toolbar = findViewById(R.id.toolbar);
        etSearch = findViewById(R.id.searchEditText);
        recyclerView = findViewById(R.id.diaryRecyclerView);
        emptyStateLayout = findViewById(R.id.emptyStateLayout);
        fabAdd = findViewById(R.id.fabAdd);
    }
    
    private void initViewModel() {
        diaryViewModel = new ViewModelProvider(this).get(DiaryViewModel.class);
    }
    
    private void setupRecyclerView() {
        diaryAdapter = new DiaryAdapter(this);
        diaryAdapter.setOnDiaryClickListener(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(diaryAdapter);
    }
    
    private void setupListeners() {
        fabAdd.setOnClickListener(v -> {
            Intent intent = new Intent(this, DiaryEditActivity.class);
            startActivity(intent);
        });
        
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String keyword = s.toString().trim();
                if (keyword.isEmpty()) {
                    observeAllDiaries();
                } else {
                    searchDiaries(keyword);
                }
            }
            
            @Override
            public void afterTextChanged(Editable s) {}
        });
    }
    
    private void observeData() {
        observeAllDiaries();
    }
    
    private void observeAllDiaries() {
        diaryViewModel.getAllDiaries().observe(this, this::updateUI);
    }
    
    private void searchDiaries(String keyword) {
        diaryViewModel.searchDiaries(keyword).observe(this, this::updateUI);
    }
    
    private void updateUI(List<DiaryEntity> diaries) {
        if (diaries == null || diaries.isEmpty()) {
            recyclerView.setVisibility(View.GONE);
            emptyStateLayout.setVisibility(View.VISIBLE);
        } else {
            recyclerView.setVisibility(View.VISIBLE);
            emptyStateLayout.setVisibility(View.GONE);
            diaryAdapter.setDiaries(diaries);
        }
    }
    
    @Override
    public void onDiaryClick(DiaryEntity diary) {
        // 点击日记项，进入阅读模式
        Intent intent = new Intent(this, DiaryReadActivity.class);
        intent.putExtra(DiaryReadActivity.EXTRA_DIARY_ID, (long) diary.getId());
        startActivity(intent);
    }
    
    @Override
    public void onDiaryLongClick(DiaryEntity diary) {
        // 长按日记项，显示删除对话框
        new AlertDialog.Builder(this)
                .setTitle("删除日记")
                .setMessage("确定要删除这篇日记吗？")
                .setPositiveButton("删除", (dialog, which) -> {
                    diaryViewModel.delete(diary);
                    Toast.makeText(this, "日记已删除", Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton("取消", null)
                .show();
    }
}